package com.bestdata.TD440.util;

import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Base64;

/**
 * java实现IEEE 754标准
 * 16进制转float
 * @author chizhenyu
 */
public class Hex2Float {

    /**
     * 将字符串转为byte数组
     * @author chizhenyu
     * @param hexString
     * @return
     */
    public static byte[] toByteArray(String hexString) {
        if (StringUtils.isEmpty(hexString))
            return null;
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() >> 1];
        int index = 0;
        for (int i = 0; i < hexString.length(); i++) {
            if (index  > hexString.length() - 1)
                return byteArray;
            byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
            byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
            byteArray[i] = (byte) (highDit << 4 | lowDit);
            index += 2;
        }
        return byteArray;
    }


    /**
     * 字节数组转float  采用IEEE 754标准
     * @param hexString
     * @return
     */
    public static String bytes2Float(String hexString){

        byte[] bytes = toByteArray(hexString);
        //获取 字节数组转化成的2进制字符串
        String BinaryStr = bytes2BinaryStr(bytes);
        //符号位S
        Long s = Long.parseLong(BinaryStr.substring(0, 1));
        //指数位E
        Long e = Long.parseLong(BinaryStr.substring(1, 9),2);
        //位数M
        String M = BinaryStr.substring(9);
        float m = 0,a,b;
        for(int i=0;i<M.length();i++){
            a = Integer.valueOf(M.charAt(i)+"");
            b = (float) Math.pow(2, i+1);
            m =m + (a/b);
        }
        Float f = (float) ((Math.pow(-1, s)) * (1+m) * (Math.pow(2,(e-127))));

        String data = new BigDecimal(f).toPlainString().substring(0,12);
        return data;
    }
    /**
     * 将字节数组转换成2进制字符串
     * @param bytes
     * @return
     */
    public static String bytes2BinaryStr(byte[] bytes){
        StringBuffer binaryStr = new StringBuffer();
        for(int i=0;i<bytes.length;i++){
            String str = Integer.toBinaryString((bytes[i] & 0xFF) + 0x100).substring(1);
            binaryStr.append(str);
        }
        return binaryStr.toString();
    }

    /**
     * ASCII转字符串
     * @return
     */
    public static String ASCII2HexStr(Object obj){
        StringBuffer sbu = new StringBuffer();
        String[] chars = obj.toString().split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }
}